package com.example.stlink.utils.httpUtils;

import android.util.Log;

import androidx.annotation.NonNull;

import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.response.BaseResponse;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public abstract class PostFileHttpUtils {

    public void FileUpload(String url, File file){
        System.out.println("POST: loading...........");
        if(file == null){
            System.out.println("POST: file is null");
            return;
        }
        //请求头
        Headers headers = new Headers.Builder()
                .add("appId", UrlConstants.APP_ID)
                .add("appSecret", UrlConstants.APP_SECRET)
                .build();
        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                // 这里设置要传给后台的参数；如果要添加多个参数，可以先获取到MultipartBody.Builder对象，然后再for循环添加
                // 约定key 如 "certificate" 作为后台接受图片的key；这里约定的key是：certificate
                .addFormDataPart(ModelFieldConstants.FILE, file.getName(), RequestBody.create(UrlConstants.MEDIA_TYPE_PNG, file))
                .build();

        //构建Request请求体
        Request.Builder RequestBuilder = new Request.Builder();
        Request request = RequestBuilder
                // 添加URL地址
                .url(url)
                .headers(headers)
                .post(multipartBody)
                .build();
        // 构建 OkHttpClient 请求对象，后面大家都很熟悉了，不多说
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                .build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }


    private final Callback callback = new Callback() {


        /**
         * 主要是连接异常错误
         * @param call 回调
         * @param e 异常
         */
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            Log.e("TAGTAG", "onFailure，图片上传失败：" + e.getMessage());
            e.printStackTrace();
        }

        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            assert response.body() != null;
            final String body = response.body().string();
            Log.e("TAGTAG", "onResponse，图片上传成功：" + body);
            Gson gson = new Gson();
            Type jsonType = new TypeToken<BaseResponse<Object>>() {}.getType();
            BaseResponse<Object> baseResponse = gson.fromJson(body, jsonType);
            int code = baseResponse.getCode();
            //页面请求成功
            if(response.code() == 200){
                if (code == 200) {
                    System.out.println("POST:nextMethod...........");
                    System.out.println("POST:code = " + baseResponse.getCode() + "...................");
                    System.out.println("baseResponse:code = " + response.code());
                    nextMethod(baseResponse);
                }else if(code == 404){
                    System.out.println("资源找不到....................");
                }else if(code == 500){
                    System.out.println("POST:failed.............");
                    System.out.println("baseResponse:msg = " + baseResponse.getMsg() + ".........................");
                    System.out.println("Response:failedMethod");
                    failedMethod(baseResponse);
                }else if(code == 5217){
                    System.out.println("没有或缺少 appId 或 appSecret...........................");
                }else if(code == 5311){
                    System.out.println("接口使用次数不够................");
                }else if(code == 5314){
                    System.out.println("请求参数不对.................");
                }else{
                    System.out.println("response:code = " + response.code());
                }
            }else if(code == 401) {
                System.out.println("未授权.........................");
            }else{
                System.out.println("response:connect...error...................");
                System.out.println("response:code = " + response.code());
                System.out.println("response: " + response);
                System.out.println("baseResponse: " + baseResponse);
            }

        }

    };

    /**
     * post成功的后续动作
     */
    public abstract void nextMethod(BaseResponse<Object> baseResponse);

    /**
     * post失败的后续动作
     */
    public abstract void failedMethod(BaseResponse<Object> baseResponse);
}
